var indexPageNum = 1;
var listPageNum = 2;
var pageNum = 2;
var $pageID;
window.onload = function () {
    'use strict';
    $(document).on("pageAnimationStart", function (e, pageId, $page) {
        $.cartNum();
        $('#bar-footer a').removeClass('active');
        $('[data-action="'+ pageId +'"]').addClass('active');
        $.closePanel();
    });
    $(document).on("pageInit", function(e, pageId, $page) {
        $pageID = pageId;
        $.lazyInit();
        switch (pageId) {
            case 'index':
                pageNum = indexPageNum;
                // $.scrollMenu();
                $.updateList();
                break;
            case 'list':
                pageNum = listPageNum;
                $.updateList();
                break;
            case 'cart':
                $.showCart();
                break;
            case 'user':
                $.initUserPage();
                break;
            case 'check':
                $.checkDeal();
                $.selectDelivery();
                break;
            case 'user-address':
                $.showAddressData();
                break;
            case 'user-order':
                $.getUserOrderList();
                break;
            case 'address-select':
                $.initAddressSelect();
                break;
            case 'time-select':
                $.initTimeSelect();
                break;
            case 'payment-stripe':
                $.initStripe();
                break;
        }
    });
    var cartPostData = [];
    var flag = 0;
    var cartData;

    $(document).on('click', '#orderAll', function () {
        console.log('This is orderAll!');
    });
    //移除遮罩
    $(document).on('click', function () {
        if (flag == 1) {
            $('.list-menu-overlay').removeAttr('style');
            $('#my-element ul').removeAttr('style');
            $('#my-element ul').addClass('hidden');
            $('#orderIcon').removeClass('fa-angle-down');
            $('#orderIcon').addClass('fa-angle-right');
            flag = 0;
        }
    });
    //监听滚动事件
    document.addEventListener('touchmove', function (event) {
        if(flag == 1) {　　　　　　　　　　　　　　　　　　　　　　　　　//判断是遮罩显示时执行，禁止滚屏
            event.preventDefault();　　　　　　　　　　　　　　　　　　//禁止浏览器默认行为
        }
    });
    /**
     * 通过代理绑定click加入和移除购物车按钮
     */
    $(document).on('click', '.plus', function (e) {
        var $num = $(this).prev();
        var num = Number($num.text());
        var parentObj = $(this).parents("li");
        if (num == 0)
        {
            $num.prev().removeClass('hidden');
        }
        $.cartImageAnimation(this);
        $num.text(num + 1);
        parentObj.attr('data-num', String(num + 1));
        //数据
        var data = {
            id: parentObj.data('id'),
            thumb: parentObj.data('thumb'),
            title: parentObj.data('title'),
            price: parentObj.data('price'),
            intro: parentObj.data('intro'),
            sv: parentObj.data('sv'),
            checked: false
        };
        $.cartStore(data, true);
        $.cartNum();
    });
    $(document).on('click', '.subtract', function (e) {
        var $num = $(this).next();
        var num = Number($num.text());
        var parentObj = $(this).parents("li");
        if (num > 0)
        {
            if (num - 1 == 0)
            {
                $(this).addClass('hidden');
                $num.text('');
                parentObj.attr('data-num', '');
            } else {
                $num.text(num - 1);
                parentObj.attr('data-num', String(num - 1));
            }
            //数据
            var data = {
                id: parentObj.data('id'),
                thumb: parentObj.data('thumb'),
                title: parentObj.data('title'),
                price: parentObj.data('price'),
                intro: parentObj.data('intro'),
                sv: parentObj.data('sv'),
                checked: false
            };
            $.cartStore(data, false);
            $.cartNum();
        } else {
            return false;
        }
    });
    /**
     * 下拉刷新页面
     */
    $(document).on('refresh', '.pull-to-refresh-content',function(e) {
        location.reload();
    });
    /**
     * 无限加载
     */
    var loading = false;
    // Last loaded index
    $(document).on('infinite', '#infinite-index', function() {

        // 如果正在加载，则退出
        if (loading) return;
        // 设置flag
        loading = true;
        var pageDatas = $('#page-data-index');
        var url = pageDatas.data('url');
        var typeID = pageDatas.data('typeid');
        var sort = pageDatas.data('sort');
        var page = indexPageNum;

        $('#infinite-index').append('<div class="infinite-scroll-preloader"><div class="preloader"></div></div>');

        $.ajax({
            url: url,
            data: {
                page:page + 1,
                typeID:typeID,
                sort:sort
            },
            type: 'GET',
            dataType: 'json',

            success: function (r) {
                if (r.code)
                {
                    var html = '';
                    var count = 0;
                    $(r.data.goods).each(function (k, v) {
                        html += '<li data-id="'+ v.id +'" data-thumb="'+ v.thumb +'" data-title="'+ v.title +'" data-price="'+ v.realAmount +'" data-intro="'+ v.abstract +'" data-sv="'+ v.hit +'" data-num="">'
                            +'<div class="item-content">'
                            +'<a href="#" class="item-slicer-link item-media">'
                            +'<img class="cart-image lazy" src="'+ v.lazyImg +'" data-original="'+ v.thumb +'">'
                            +'</a>'
                            +'<div class="item-inner">'
                            +'<div class="item-title-row no-icon">'
                            +'<div class="item-title">'+ v.title +'</div>'
                            +'<div class="item-after">'+ v.realAmount +' 円</div>'
                            +'</div>'
                            +'<div class="item-subtitle">販売量 '+ v.hit +' 件</div>'
                            +'<div class="item-text">'+ v.abstract +'</div>'
                            +'<div class="item-buy">'
                            +'<div class="row no-gutter">'
                            +'<div class="col-40"></div>'
                            +'<div class="col-20 subtract hidden">'
                            +'<i class="fa fa-cart-arrow-down fa-2x"></i>'
                            +'</div>'
                            +'<div class="col-20"></div>'
                            +'<div class="col-20 plus">'
                            +'<i class="fa fa-cart-plus fa-2x"></i>'
                            +'</div>'
                            +'</div>'
                            +'</div>'
                            +'</div>'
                            +'</div>'
                            +'</li>';
                        if (++count === r.data.goods.length) {
                            pageDatas.find('ul').append(html);
                        }
                    });
                    $('.infinite-scroll-preloader').remove();
                } else {
                    // 加载完毕，则注销无限加载事件，以防不必要的加载
                    $.detachInfiniteScroll($('.infinite-scroll'));
                    // 删除加载提示符
                    $('.infinite-scroll-preloader').remove();
                    // return;
                }
                ++page;
                // ++pageNum;
                indexPageNum = page;
                //容器发生改变,如果是js滚动，需要刷新滚动
                $.refreshScroller();
                $.updateList();
                // 重置加载flag
                loading = false;
            }
        });
    });

    /**
     * 无限加载
     */
    var loadingList = false;
    // Last loaded index
    $(document).on('infinite', '#infinite-list', function() {

        // 如果正在加载，则退出
        if (loadingList) return;

        // 设置flag
        loadingList = true;
        var pageDatas = $('#page-data-list');
        var url = pageDatas.data('url');
        var typeID = pageDatas.data('typeid');
        var sort = pageDatas.data('sort');
        var pagePage = Number(pageDatas.find("input[name='page']").val());
        var recommendID = pageDatas.data('recommendid');

        $('#infinite-list').append('<div class="infinite-scroll-preloader"><div class="preloader"></div></div>');

        $.ajax({
            url: url,
            data: {
                page:pagePage + 1,
                typeID:typeID,
                recommendID:recommendID,
                sort:sort
            },
            type: 'GET',
            dataType: 'json',

            success: function (r) {
                if (r.code)
                {
                    var html = '';
                    var count = 0;
                    $(r.data.goods).each(function (k, v) {
                        html += '<li data-id="'+ v.id +'" data-thumb="'+ v.thumb +'" data-title="'+ v.title +'" data-price="'+ v.realAmount +'" data-intro="'+ v.abstract +'" data-sv="135" data-num="">'
                            +'<div class="item-content">'
                            +'<a href="#" class="item-slicer-link item-media">'
                            +'<img class="cart-image lazy" src="'+ v.lazyImg +'" data-original="'+ v.thumb +'">'
                            +'</a>'
                            +'<div class="item-inner">'
                            +'<div class="item-title-row no-icon">'
                            +'<div class="item-title">'+ v.title +'</div>'
                            +'<div class="item-after">'+ v.realAmount +' 円</div>'
                            +'</div>'
                            +'<div class="item-subtitle">販売量 '+ v.hit +' 件</div>'
                            +'<div class="item-text">'+ v.abstract +'</div>'
                            +'<div class="item-buy">'
                            +'<div class="row no-gutter">'
                            +'<div class="col-40"></div>'
                            +'<div class="col-20 subtract hidden">'
                            +'<i class="fa fa-cart-arrow-down fa-2x"></i>'
                            +'</div>'
                            +'<div class="col-20"></div>'
                            +'<div class="col-20 plus">'
                            +'<i class="fa fa-cart-plus fa-2x"></i>'
                            +'</div>'
                            +'</div>'
                            +'</div>'
                            +'</div>'
                            +'</div>'
                            +'</li>';
                        if (++count === r.data.goods.length) {
                            pageDatas.find('ul').append(html);
                        }
                    });
                    $('.infinite-scroll-preloader').remove();
                } else {
                    // 加载完毕，则注销无限加载事件，以防不必要的加载
                    $.detachInfiniteScroll($('.infinite-scroll'));
                    // 删除加载提示符
                    $('.infinite-scroll-preloader').remove();
                    // return;
                }
                ++pagePage;
                pageDatas.find("input[name='page']").val(pagePage);
                //容器发生改变,如果是js滚动，需要刷新滚动
                $.refreshScroller();
                $.updateList();
                // 重置加载flag
                loadingList = false;
            }
        });
    });
    /***********************************************************************
     * 懒加载
     ***********************************************************************/
    $.lazyLoadObj = function () {
        $('.lazy').lazyload({
            effect : "fadeIn"
        });
    }
    $.lazyInit = function () {
        $.lazyLoadObj();
        $('.infinite-scroll').on('scroll', $.lazyLoadObj);
        $('.infinite-scroll').on('resize', $.lazyLoadObj);
    }
    /***********************************************************************
     * Cart页面
     ***********************************************************************/
    /**
     * 全部勾选
     */
    $(document).on('change', '#checkAll input', function () {
        var checkedCheck = $(this).is(':checked');
        $('#cart-list .label-checkbox input').prop("checked", checkedCheck);
        $.sumCart();
    });
    /**
     * 勾选单个商品
     */
    $(document).on('change', '#cart-list .label-checkbox input', function () {
        $.sumCart();
    });
    /**
     * 删除选中物品
     */
    $(document).on('click', '#cart-page-delete', function () {
        $.confirm('商品を削除しますか?', function () {
            $.delCart();
        });
    });

    /**
     * 购物车数量显示
     */
    $.cartNum = function () {
        cartData = $.getCartStore();
        if (cartData != null)
        {
            $('#cartIcon .badge').text(cartData.length);
            $('#cartIcon .badge').removeClass('hidden');
        } else {
            $('#cartIcon .badge').text(0);
            $('#cartIcon .badge').addClass('hidden');
        }
    };
    /**
     * 添加到购物车动画
     * @param oldObj
     */
    $.cartImageAnimation = function (oldObj) {
        //获取原始目标
        var cartImage = $(oldObj).parents('.item-content').find('.cart-image');
        //获取原始图片
        var img = cartImage.attr('src');
        //构造动画对象
        var flyer = $('<img class="u-flyer" src="'+img+'">');
        flyer.css({'top':cartImage.offset().top, 'left':cartImage.offset().left});
        $('#bar-footer').after(flyer);
        //获取终点坐标
        var fTop = $('#cartIcon').offset().top + 15;
        var fLeft = $('#cartIcon').offset().left + 45;
        //开始动画
        flyer.animate({
            opacity: 0.25, left: fLeft + 'px', top: fTop + 'px', width: '5px', height: '5px',
            color: '#abcdef'
        }, 1000, 'ease-out', function () {
            //动画结束后删除对象
            flyer.remove();
        });
    };

    /***********************************************************************
     * 购物车数据
     ***********************************************************************/
    var cartKey = 'lt'; //购物车数据的键
    /**
     * cartStore操作
     * @param data  数据对象
     * @param bool cartFun  true=添加/false=移除
     * @returns {boolean}
     */
    $.cartStore = function (data, cartFun) {
        var oldData = store.get(cartKey);
        var newData = oldData != undefined ? oldData : [];
        var check = true;
        if (cartFun) {
            for (var x in newData)
            {
                if(newData[x].id == data.id)
                {
                    check = false;
                    newData[x].num = newData[x].num + 1;
                }
            }
            if (oldData == undefined || check) {
                data.num = 1;
                newData.push(data);
            }
        } else {
            if (oldData == undefined)
                return false;
            for (var x in newData)
            {
                if(newData[x].id == data.id)
                {
                    newData[x].num = newData[x].num - 1;
                    if (!newData[x].num) {
                        newData.splice(x,1);
                    }
                }
            }
            if (newData.length == 0)
            {
                store.remove(cartKey);
                return true;
            }
        }
        store.set(cartKey, newData);
        return true;
    };
    /**
     * 获取本地数据
     * @returns cartData
     */
    $.getCartStore = function () {
        var storeData = store.get(cartKey);
        return (storeData != undefined) ? storeData : null;
    };
    /**
     * 更新选购列表的状态
     *
     */
    $.updateList = function () {
        cartData = $.getCartStore();
        var $subtract = $('.media-list ul li .subtract');
        $subtract.addClass('hidden');
        $subtract.next().text('');
        if (cartData != null)
        {
            $.each(cartData, function (k, v) {
                var $thisSub = $('.media-list ul [data-id="'+ v.id +'"] .subtract');
                $thisSub.removeClass('hidden');
                $thisSub.next().text(v.num);
            });
        }
    };
    /*
    显示购物车物品
     */
    $.showCart = function () {
        cartData = $.getCartStore();
        if (cartData) {
            $('.cart-empty').addClass('hidden');
            $('.cart-footer').removeClass('hidden');
            var listHtml = '';
            var num = 0;
            var total = 0;
            var checkAll = true;
            $.each(cartData, function (k, v) {
                if (v.checked)
                {
                    num += 1;
                    total += v.num * v.price;
                } else {
                    checkAll = false;
                }
                var check = v.checked ? 'checked' : '';
                // console.log(v);
                listHtml += '<li><label class="label-checkbox item-content">'
                            +'<input name="id[]" value="'+ v.id +'" type="checkbox" name="my-radio" '+ check +'>'
                            +'<div class="item-media"><i class="icon icon-form-checkbox"></i></div>'
                            +'<img class="cart-image" src="'+ v.thumb +'">'
                            +'<div class="item-inner"><div class="item-title-row">'
                            +'<div class="item-title">'+ v.title +' x '+ v.num +'</div><div class="item-after">'+ (v.price*v.num).toFixed(0) +' 円</div>'
                            +'</div><div class="item-text">'+ v.intro +'</div></div>'
                            +'</label></li>';
            });
            $('#cart-list ul').html(listHtml);
            $('#cart-list').removeClass('hidden');
            //合计等
            $('#cart-page-sum').text(num);
            $('#cart-page-total').text(total.toFixed(0));
            $('#checkAll input').prop("checked", checkAll);
        } else {
            $('.cart-empty').removeClass('hidden');
            $('#cart-list').addClass('hidden');
            $('.cart-footer').addClass('hidden');
        }
    };

    /**
     * 计算并更新选中购买商品
     */
    $.sumCart = function () {
        var $cartList = $('#cart-list .label-checkbox input[type="checkbox"]:checked');
        var idArr = [];
        var newData = cartData != undefined ? cartData : [];
        var num = 0;
        var total = 0;
        var checkAll = true;
        $.each($cartList, function (k, v) {
            idArr.push(Number($(v).val()));
        });

        //获取选中物品
        $.each(cartData, function (k, v) {
            if (idArr.indexOf(v.id) > -1) {
                newData[k].checked = true;
                num += 1;
                total += v.num * v.price;
            } else {
                newData[k].checked = false;
                checkAll = false;
            }
        });
        if (newData.length != 0)
            store.set(cartKey, newData);
        //选中物品的合计
        $('#cart-page-sum').text(num);
        $('#cart-page-total').text(total.toFixed(0));
        $('#checkAll input').prop("checked", checkAll);
    };
    /**
     * 判断是否有选中购物车中的商品
     * @returns {*}
     */
    $.checkSelected = function () {
        var $cartList = $('#cart-list .label-checkbox input[type="checkbox"]:checked');
        return !!$cartList.length;
    }

    $.delCart = function () {
        console.log($.checkSelected());
        var $cartList = $('#cart-list .label-checkbox input[type="checkbox"]:checked');
        var idArr = [];
        var newData = cartData != undefined ? cartData : [];
        $.each($cartList, function (k, v) {
            idArr.push(Number($(v).val()));
        });
        if (idArr.length == 0)
            return false;
        //删除选中
        for (var x in newData)
        {
            for (var y in idArr)
            {
                if (idArr[y] == newData[x].id)
                {
                    newData.splice(x,1);
                }
            }
        }
        console.log(newData.length);
        if (newData.length == 0)
        {
            store.remove(cartKey);
        } else {
            store.set(cartKey, newData);
        }
        $.showCart();
        $.cartNum();
        $.sumCart();
    };


    /**
     * 结算check页面
     */
    $.checkDeal = function () {
        cartData = $.getCartStore();
        if (cartData) {
            var listHtml = '';
            var total = Number($('#delivery span').text());
            $.each(cartData, function (k, v) {
                if (v.checked)
                {
                    listHtml += '<li class="item-content">'
                        +'<div class="item-inner row no-gutter">'
                        +'<div class="col-60">'+ v.title +'</div>'
                        +'<div class="col-20" style="text-align: left">x '+ v.num +'</div>'
                        +'<div class="col-20" style="text-align: right">'+ (v.num * v.price).toFixed(0) +' 円</div>'
                        +'</div>'
                        +'</li>';
                    total += v.num * v.price;
                }
            });
            $('#check-list ul').html(listHtml);
            //合计等
            $('#cart-page-total').text(total.toFixed(0));
        }
    }

    /**
     * 激活配送时间选择
     */
    $.selectDelivery = function () {
        var url = $('#page-data').data('url');
        $.ajax({
            url: url,
            type: 'GET',
            dataType: 'json',
            success: function (r) {
                var addressData = [];
                var addressArr = [];
                var timeData = [];
                var timeArr = [];
                $(r.data.address).each(function (index, value) {
                    addressData[index] = value.name +' '+ value.phone +' '+ value.address;
                    addressArr[index] = value;
                });
                $(r.data.time).each(function (index, value) {
                    timeData[index] = value.time;
                    timeArr[index] = value;
                });
                //获取COOKIE
                var deal_time = store.get('deal_time');
                var deal_address = store.get('deal_address');
                if (deal_time != undefined)
                {
                    $('#delivery').data('id', timeArr[deal_time].id);
                    $('#delivery .item-title').text(timeArr[deal_time].time);
                    $('#delivery span').text(timeArr[deal_time].price);
                    $.checkDeal();
                }
                if (deal_address != undefined)
                {
                    $('#address').data('id', addressArr[deal_address].id);
                    $('#address .item-subtitle').text(addressArr[deal_address].name + ' ' + addressArr[deal_address].phone);
                    $('#address .item-text').text(addressArr[deal_address].address);
                    $.checkDeal();
                }

                // $("#picker").picker({
                //     toolbarTemplate: '<header class="bar bar-nav">\
                //       <button class="button button-link pull-right close-picker">确定</button>\
                //       <h1 class="title">配送时间选择</h1>\
                //       </header>',
                //     cols: [
                //         {
                //             textAlign: 'center',
                //             values: timeData
                //         }
                //     ],
                //     formatValue: function (picker, value, displayValue) {
                //
                //         var k = $.inArray(displayValue[0], picker.cols[0].values);
                //         //插入对应的价格
                //         $("#delivery").data('id', timeArr[k].id);
                //         $('#delivery').find('.item-title').text(timeArr[k].time);
                //         $('#delivery').find('span').text(timeArr[k].price);
                //         $.checkDeal();
                //         store.set('deal_time', k);
                //         return displayValue;
                //     }
                // });
                // $("#picker-address").picker({
                //     //language=HTML
                //     toolbarTemplate: '<header class="bar bar-nav">\
                //   <button class="button button-link pull-left close-picker" onclick="\$\.router\.load(\'/shop/user/address-add\')">添加地址</button>\
                //   <button class="button button-link pull-right close-picker">确定</button>\
                //   <h1 class="title">配送地址选择</h1>\
                //   </header>',
                //     cols: [
                //         {
                //             textAlign: 'center',
                //             values: addressData
                //         }
                //     ],
                //     formatValue: function (picker, value, displayValue) {
                //         var k = $.inArray(displayValue[0], picker.cols[0].values);
                //         //插入对应的价格
                //         $('#address').data('id', addressArr[k].id);
                //         $('#address .item-subtitle').text(addressArr[k].name + ' ' + addressArr[k].phone);
                //         $('#address .item-text').text(addressArr[k].address);
                //         $.checkDeal();
                //         store.set('deal_address', k);
                //         return displayValue;
                //     }
                // });
            }
        });
    };

    $.initAddressSelect = function () {
        var url = $('#address-select').data('url');
        $.ajax({
            url: url,
            type: 'GET',
            dataType: 'json',
            success: function (r) {
                if (r.code)
                {
                    var listHtml = '';
                    $.each(r.data.address, function (k, v) {
                        listHtml += '<li><label class="label-checkbox item-content">'
                            +'<input id="address-select-'+ k +'" type="radio" name="id" value="'+ k +'">'
                            +'<div class="item-media"><i class="icon icon-form-checkbox"></i></div>'
                            +'<div class="item-inner"><div class="item-title-row">'
                            +'<div class="item-subtitle">'+ v.name +' '+ v.phone +'</div>'
                            +'<div class="item-text">'+ v.address +'</div>'
                            +'</div></div></label></li>';
                    });
                    $('#address-select .list-block ul').html(listHtml);
                    var addressID = store.get('deal_address');
                    addressID = (addressID != undefined) ? addressID : null;
                    if (addressID)
                    {
                        $('#address-select-' + addressID).attr("checked","true");
                    }
                } else {
                    $.toast(r.msg);
                }
            }
        });
    };
    $.addressSelect = function () {
        var $select = $('#address-select .list-block ul li input[name="id"]:checked');
        var addressID = $select.val();
        if (addressID === undefined)
        {
            $.toast("商品受取住所を選択");
            return false;
        }
        store.set('deal_address', addressID);
        $.router.load("/deal/check");
    };

    $.initTimeSelect = function () {
        var url = $('#time-select').data('url');
        $.ajax({
            url: url,
            type: 'GET',
            dataType: 'json',
            success: function (r) {
                if (r.code)
                {
                    var listHtml = '';
                    $.each(r.data.timeData, function (k, v) {
                        listHtml += '<li><label class="label-checkbox item-content">'
                            +'<input id="time-select-'+ k +'" type="radio" name="id" value="'+ k +'">'
                            +'<div class="item-media"><i class="icon icon-form-checkbox"></i></div>'
                            +'<div class="item-inner">'
                            +'<div class="item-subtitle">'+ v.time +'</div>'
                            +'<div class="item-text">'+ v.price +' 円</div>'
                            +'</div></label></li>';
                    });
                    $('#time-select .list-block ul').html(listHtml);
                    var timeID = store.get('deal_time');
                    timeID = (timeID != undefined) ? timeID : null;
                    if (timeID)
                    {
                        $('#time-select-' + timeID).attr("checked","true");
                    }
                } else {
                    $.toast(r.msg);
                }
            }
        });
    };
    $.timeSelect = function () {
        var $select = $('#time-select .list-block ul li input[name="id"]:checked');
        var pTime = $select.val();
        if (pTime === undefined)
        {
            $.toast("配送時間を選択してください");
            return false;
        }
        store.set('deal_time', pTime);
        $.router.load("/deal/check");
    };

    /**
     * 创建订单
     * @param url
     * @returns {boolean}
     */
    $.createOrder = function (url) {
        var addressID = $('#address').data('id');
        var delivery = $('#delivery').data('id');
        var remark = $("textarea[name='remark']").val();
        if (addressID === '')
        {
            $.toast("受取住所を選択してください");
            return false;
        }
        if (delivery === '')
        {
            $.toast("配送時間を選択してください");
            return false;
        }
        //获取购买项
        cartData = $.getCartStore();
        var orderData = [];
        if (cartData) {
            $.each(cartData, function (k, v) {
                if (v.checked)
                {
                    orderData.push({id:v.id,num:v.num});
                }
            });
        }
        $.ajax({
            url: url,
            data: {
                addressID:addressID,
                delivery:delivery,
                remark:remark,
                orderData:orderData
            },
            type: 'POST',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            dataType: 'json',
            success: function (r) {
                if (r.code)
                {
                    $.router.load("/deal/payment-stripe?code=" + r.order);
                } else {
                    $.toast(r.msg);
                }
            }
        });
    };

    $.showAddressData = function () {
        var url = $('#user-address-add-data').data('url');
        console.log(url);
        $.ajax({
            url: url,
            type: 'GET',
            dataType: 'json',
            success: function (r) {
                if (r.code)
                {
                    var listHtml = '';
                    $.each(r.data, function (k, v) {
                        listHtml += '<li class="item-link item-content" onclick="\$\.router\.load(\'/user/address-edit/'+ v.id +'\')">'
                            +'<div class="item-inner">'
                            +'<div class="item-subtitle">'+ v.name +' '+ v.phone +'</div>'
                            +'<div class="item-text">'+ v.address +'</div>'
                            +'</div>'
                            +'</li>';
                    });
                    $('#user-address-add-data ul').html(listHtml);
                } else {
                    $.toast(r.msg);
                }
            }
        });
    };
    var createAddressAjaxCheck = true;
    $.createAddress = function (url) {
        var name = $("input[name='name']").val();
        var phone = $("input[name='phone']").val();
        var school = $("select[name='school']").val();
        var address = $("input[name='address']").val();
        if(name === '' || phone === '' || school === 0 || address === '')
        {
            $.toast('情報不足');
            return false;
        }
        if (createAddressAjaxCheck)
        {
            createAddressAjaxCheck = false;
            $.ajax({
                url: url,
                data: {
                    name:name,
                    phone:phone,
                    school:school,
                    address:address
                },
                type: 'POST',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                dataType: 'json',
                success: function (r) {
                    createAddressAjaxCheck = true;
                    if (r.code)
                    {
                        $.toast(r.msg,1000);
                        setTimeout("$.router.back()",1000);
                    } else {
                        $.toast(r.msg);
                    }
                }
            });
        }
    };
    /**
     * 更新地址
     * @returns {boolean}
     */
    var updateAddressAjaxCheck = true;
    $.updateAddress = function (url) {
        var name = $("input[name='name']").val();
        var phone = $("input[name='phone']").val();
        var school = $("select[name='school']").val();
        var address = $("input[name='address']").val();
        if(name === '' || phone === '' || school === 0 || address === '')
        {
            $.toast('情報不足');
            return false;
        }
        if (updateAddressAjaxCheck)
        {
            updateAddressAjaxCheck = false;
            $.ajax({
                url: url,
                data: {
                    name:name,
                    phone:phone,
                    school:school,
                    address:address
                },
                type: 'POST',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                dataType: 'json',
                success: function (r) {
                    updateAddressAjaxCheck = true;
                    if (r.code)
                    {
                        $.toast(r.msg,1000);
                        setTimeout("$.router.back()",1000);
                    } else {
                        $.toast(r.msg);
                    }
                }
            });
        }
    };

    /**
     * 随屏目录
     */
    $.scrollMenu = function () {
        var documentHeight = $('.list-menu').offset().top + $('.content').scrollTop();
        //是否支持sticky
        if (CSS.supports("position", "sticky") || CSS.supports("position", "-webkit-sticky")) {
            //支持sticky
        } else {
            $('html').addClass('fixed-supported');
            $('#my-element').addClass('fixedsticky-fix');
            //滚动事件
            $('.content').on('scroll', function(){
                //do something here on page scroll
                var scrollTop = $(this).scrollTop();
                if (scrollTop - documentHeight >= -44)
                {
                    //$('.list-menu').addClass('list-menu-fixed');
                    $('.list-menu-placeholder').removeClass('hidden');
                    $('#my-element').addClass('fixedsticky-on');
                    $('#my-element').removeClass('fixedsticky-off');
                } else {
                    //$('.list-menu').removeClass('list-menu-fixed');
                    $('.list-menu-placeholder').addClass('hidden');
                    $('#my-element').addClass('fixedsticky-off');
                    $('#my-element').removeClass('fixedsticky-on');
                }
            });
        }
    };
    /**
     * user-order页面初始化
     */
    $.getUserOrderList = function () {
        var url = $('#user-order-data').data('url');
        $.ajax({
            url: url,
            type: 'GET',
            dataType: 'json',
            success: function (r) {
                if (r.code)
                {
                    $('#user-order-data').html(r.data.orderHtml);
                    $('#user-order-data').data('page', r.data.page);
                }
            }
        });
    };
    /**
     * 订单列表无限加载
     * @type {boolean}
     */
    var userOrderDataLoading = false;
    $(document).on('infinite', '#user-order-data',function() {

        // 如果正在加载，则退出
        if (userOrderDataLoading) return;

        // 设置flag
        userOrderDataLoading = true;
        var url = $('#user-order-data').data('url');
        var page = $('#user-order-data').data('page');

        $('.user-order-data').append('<div class="infinite-scroll-preloader"><div class="preloader"></div></div>');

        $.ajax({
            url: url,
            data: {
                page:page
            },
            type: 'GET',
            dataType: 'json',
            success: function (r) {
                if (r.code)
                {
                    $('#user-order-data').append(r.data.orderHtml);
                    $('#user-order-data').data('page', r.data.page);
                    $('.infinite-scroll-preloader').remove();
                } else {
                    // 加载完毕，则注销无限加载事件，以防不必要的加载
                    $.detachInfiniteScroll($('.infinite-scroll'));
                    // 删除加载提示符
                    $('.infinite-scroll-preloader').remove();
                    // return;
                }

                // 重置加载flag
                userOrderDataLoading = false;
                //容器发生改变,如果是js滚动，需要刷新滚动
                $.refreshScroller();
            }
        });
    });
    /**
     * 删除已购买物品
     * @param oid
     */
    $.delOrderCart = function (oid) {
        var newData = cartData = $.getCartStore();
        if (cartData)
        {
            $.each(cartData, function (k, v) {
                if ($.inArray(v.id, oid) >= 0)
                    newData.splice(k,1);
            });
        }
        if (newData.length == 0)
        {
            store.remove(cartKey);
        } else {
            store.set(cartKey, newData);
        }
    };
    /**
     * 签到
     * @type {boolean}
     */
    var signButtonCheck = true;
    $.signButton = function (url) {
        if (signButtonCheck)
        {
            signButtonCheck = false;
            $.ajax({
                url: url,
                type: 'get',
                dataType: 'json',
                success: function (data) {
                    if (data.code)
                    {
                        $('#sign-button').addClass('disabled');
                        $('#sign-button').text(' チェックイン済み ');
                        $('#sign-show').html('連続チェックイン：'+ data.data.signNum +' 日<span>最終チェックイン日時: '+ data.data.signTime +'</span>');
                        $('#sign-integral').text('所有ポイント：' + data.data.integral);
                        $.toast(data.msg);
                    } else {
                        signButtonCheck = true;
                    }
                }
            });
        }
    };
    /**
     * 选择区域
     * @type {boolean}
     */
    var selectStoreCheck = true;
    $.selectStore = function (url) {
        var $select = $('#store-select .list-block ul li input[name="id"]:checked');
        var storeID = Number($select.val());
        if (storeID)
        {
            selectStoreCheck = false;
            $.ajax({
                url:url,
                type:'GET',
                data:{
                    id:storeID
                },
                dataType: 'json',
                success: function (r) {
                    if (r.code)
                    {
                        store.remove(cartKey);
                        $.alert('選択成功！', function () {
                            $.router.load('/', true);
                        });
                    }
                    selectStoreCheck = true
                }
            });
        } else {
            console.log('error');
        }

    };
    $.initUserPage = function () {
        var url = $('#user').data('upurl');
        $.ajax({
            url:url,
            type:'GET',
            dataType: 'json',
            success: function (r) {
                if (r.code)
                {
                    $('#storeName').text(r.data.storeName);
                    $('#signTip').html(r.data.signTip);
                }
            }
        });
    };

    var stripePayCheck = true;
    var stripeTokenCheck = true;
    $.initStripe = function () {
        // Create a Stripe client
        var stripe = Stripe('pk_live_8iX0c9ZC8OSghk8XZ3mhLZn3');

        // Create an instance of Elements
        var elements = stripe.elements();

        // Custom styling can be passed to options when creating an Element.
        // (Note that this demo uses a wider set of styles than the guide below.)
        var style = {
            base: {
                color: '#32325d',
                lineHeight: '24px',
                fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
                fontSmoothing: 'antialiased',
                fontSize: '16px',
                '::placeholder': {
                    color: '#aab7c4'
                }
            },
            invalid: {
                color: '#fa755a',
                iconColor: '#fa755a'
            }
        };
        var card = null;
        // Create an instance of the card Element
        card = elements.create('card', {hidePostalCode: true, style: style});

        // Add an instance of the card Element into the `card-element` <div>
        card.mount('#card-element');

        // Handle real-time validation errors from the card Element.
        card.addEventListener('change', function(event) {
            var displayError = document.getElementById('card-errors');
            if (event.error) {
                displayError.textContent = event.error.message;
            } else {
                displayError.textContent = '';
            }
        });

        $(document).on('click','#stripeSubmit', function () {
            if(stripeTokenCheck)
            {
                stripeTokenCheck = false;
                stripe.createToken(card).then(function(result) {
                    if (result.error) {
                        // Inform the user if there was an error
                        var errorElement = document.getElementById('card-errors');
                        errorElement.textContent = result.error.message;
                        stripeTokenCheck = true;
                    } else {
                        // Send the token to your server
                        stripeTokenHandler(result.token);
                    }
                });
            }
        });

    };

    function stripeTokenHandler(token) {
        var url = $("input[name='url']").val();
        var code = $("input[name='code']").val();
        if(stripePayCheck)
        {
            stripePayCheck = false;
            $.showPreloader('支付中');
            $.ajax({
                url: url,
                type: 'POST',
                dataType: 'json',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                data: {
                    code: code,
                    stripeToken:token.id
                },
                success: function (data) {
                    $.hidePreloader();
                    if (data.code)
                    {
                        $.alert('支払成功！', function () {
                            $.delOrderCart(data.oid);
                            $.showPreloader('ロード中');
                            setTimeout(function () {
                                $.router.load('/user/user-order');
                            }, 3000);
                        });
                    } else {
                        $.alert(data.msg, function () {
                            $.router.load('/user/user-order');
                        });
                        stripePayCheck = true;
                        stripeTokenCheck = true;
                    }
                }
            });
        }
    }
    //初始化
    $.init();
    //初始化购物车
    $.cartNum();
    var WXPaymentCheck = true;
    $.WXPayment = function(url, code) {
        if (WXPaymentCheck)
        {
            WXPaymentCheck = false;
            $.ajax({
                url: url,
                type: 'POST',
                dataType: 'json',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                data: {
                    code: code
                },
                success: function (data) {
                    if (data.code)
                    {
                        WeixinJSBridge.invoke(
                            'getBrandWCPayRequest', data.config, function(res) {
                                switch(res.err_msg) {
                                    case 'get_brand_wcpay_request:cancel':
                                        $.alert('支払取消！');
                                        break;
                                    case 'get_brand_wcpay_request:fail':
                                        $.alert('支払失敗！（'+res.err_desc+'）');
                                        break;
                                    case 'get_brand_wcpay_request:ok':
                                        $.alert('支払成功！', function () {
                                            $.delOrderCart(data.oid);
                                            $.router.load('/user/user-order');
                                        });
                                        break;
                                    default:
                                        $.alert('エラー');
                                        break;
                                }
                            }
                        );
                    } else {
                        $.alert(data.msg, function () {
                            $.router.load('/user/user-order');
                        });
                    }
                    WXPaymentCheck = true;
                }
            });
        }
    };

};